//
//  ForgetPwdViewController.m
//  SITABLE
//
//  Created by songjun on 16/10/10.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "ForgetPwdViewController.h"

@interface ForgetPwdViewController ()

@end

@implementation ForgetPwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedStringFromTable(@"ForgetPwd", @"InfoPlist", nil);
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesAction:)];
    
    [self.view addGestureRecognizer:tapGes];
    
    if (_isSetUp) {
        botomView.hidden = YES;
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//单击收回键盘
-(void)tapGesAction:(UITapGestureRecognizer *)ges
{
    [mobileTf resignFirstResponder];
    [getYZMTf resignFirstResponder];
    [newPwdTf resignFirstResponder];
    [newPwdConfermTf resignFirstResponder];
    
    
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    mobileIv.layer.borderWidth = 1.0;
    mobileIv.layer.borderColor = UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor ;
    
    getViaIv.layer.borderWidth = 1.0;
    getViaIv.layer.borderColor = UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor ;
    
    newPwdIv.layer.borderWidth = 1.0;
    newPwdIv.layer.borderColor =UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor ;
    
    conformPwdIv.layer.borderWidth = 1.0;
    conformPwdIv.layer.borderColor = UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor ;
    
    getYzmBtn.layer.borderWidth = 1.0;
    getYzmBtn.layer.borderColor = UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor ;
    
    determinBtn.layer.borderWidth = 1.0;
    determinBtn.layer.borderColor = UIColorHexRGBA(linBoardSepLineColor, 1.0).CGColor ;
    
    [mobileTf setValue:UIColorHexRGBA(linBoardSepLineColor, 1.0) forKeyPath:@"_placeholderLabel.textColor"];
    
    [getYZMTf setValue:UIColorHexRGBA(linBoardSepLineColor, 1.0)  forKeyPath:@"_placeholderLabel.textColor"];
    [newPwdTf setValue:UIColorHexRGBA(linBoardSepLineColor, 1.0)  forKeyPath:@"_placeholderLabel.textColor"];
    [newPwdConfermTf setValue:UIColorHexRGBA(linBoardSepLineColor, 1.0)  forKeyPath:@"_placeholderLabel.textColor"];
}



//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, -height/4, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    float duaration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duaration animations:^{
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }];
}



-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
}

- (IBAction)yesAction:(UIButton *)sender
{
    
    [mobileTf resignFirstResponder];
    [getYZMTf resignFirstResponder];
    [newPwdTf resignFirstResponder];
    [newPwdConfermTf resignFirstResponder];
    
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"提交......";
    hud.tag = 1302;
    hud.mode =MBProgressHUDModeText;
    [self.view addSubview:hud];
    [hud show:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSString *mUrl = [NSString stringWithFormat:@"%@%@",linboardBaseUrl,linboardChangePwd];
    NSDictionary *parametersDic = [NSDictionary dictionaryWithObjectsAndKeys:mobileTf.text,@"mobile",newPwdTf.text,@"password",getYZMTf.text,@"smscode",nil];
    
    [manager POST:mUrl parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *errorcode = [responseObject valueForKey:@"errorCode"];
        if ([errorcode isEqualToString:@"0"]) {
            NSDictionary *infdic = [responseObject valueForKey:@"data"];
            
            ResisterObj *bettryInfo = [ResisterObj mj_objectWithKeyValues:infdic];

            //NSLog(@"%@",infdic);
            [[NSUserDefaults standardUserDefaults] setValue:[infdic valueForKey:@"imPassword"] forKey:@"LinBardUserImPwd"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"registerSuccessNoty" object:bettryInfo];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        [hud removeFromSuperview];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        hud.labelText = @"修改失败了!";
        [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:1.5f];
        ;
    }];
}

-(void)dismissHud1302
{
    MBProgressHUD *hud = [self.view viewWithTag:1302];
    if (hud) {
        [hud removeFromSuperview];
    }
}



- (IBAction)haveAccountAction:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)isPureNumandCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}


- (IBAction)getYZMAciton:(UIButton *)sender
{
    MBProgressHUD *mbhud = [[MBProgressHUD alloc] initWithView:self.view];
    mbhud.mode = MBProgressHUDModeText;
    mbhud.labelText = @"请求验证码......";
    mbhud.tag = 1302;
    [self.view addSubview:mbhud];
    
    [mbhud show:YES];
    mobileTf.text = [mobileTf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (mobileTf.text.length == 0) {
        mbhud.labelText = @"请填写手机号";
        [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:1.5f];
        return;
    }
    
    BOOL isMobile = [self isPureNumandCharacters:mobileTf.text];
    
    if (!isMobile||mobileTf.text.length!=11) {
        mbhud.labelText = @"手机号不合法";
        [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:1.5f];
        return;
    }
    
    if ([[sender titleLabel].text isEqualToString:@"获取验证码"]) {
        //向服务端rest接口获取验证码
        //SitaShortMessageCer
        [self getSortMessageFromnet];
    }
    
    __block int timeout=120;//倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }else{
            sender.userInteractionEnabled = NO;
            int seconds = timeout % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *tittleString = [NSString stringWithFormat:@"%d秒",seconds];
                if ([tittleString isEqualToString:@"0秒"]) {
                    //更新ui
                    [sender setTitle:@"120秒" forState:UIControlStateNormal];
                }else{
                    //更新ui
                    [sender setTitle:tittleString forState:UIControlStateNormal];
                }
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);

}

-(void)getSortMessageFromnet
{
    
    MBProgressHUD *hud = [self.view viewWithTag:1302];
    hud.labelText = @"获取验证码";
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10.0f];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *mUrl = [NSString stringWithFormat:@"%@%@%@%@",linboardBaseUrl,linboardGetViaCode,mobileTf.text,@"?type=1"];
    //NSLog(@"****:%@",mUrl);
    [manager GET:mUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *infdic = [responseObject valueForKey:@"data"] ;
        //NSLog(@"%@",infdic);
        [hud removeFromSuperview];
        ;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        hud.labelText = @"获取验证码失败!";
        [self performSelector:@selector(dismissHud1302) withObject:nil afterDelay:1.5f];
    }];
    
    
    
    
}


@end
